from . import mon_bp
from flask import render_template,jsonify,make_response,request
from flask_restful import Api,Resource
from model.monitor import cpu_t
from lib.response import response
from mail.mail_warn import warn
from model.user import host

api = Api(mon_bp)

class cpu(Resource):
    def get(self,id = None):
        if id is None:
            result = cpu_t.get()
        else:
            result = cpu_t.get_by_id(id)
        result = response(data=result,message="get cpu innfo success")
        # return result
        return make_response(render_template('cpu_monitor.html',data = result),200)

    def post(self):
        hostname = request.json.get("hostname")
        date = request.json.get("date")
        cpu_core = request.json.get("cpu_core")
        cpu_used = request.json.get("cpu_used")
        cpu_free = request.json.get("cpu_free")

        cpu_t.create(hostname,date,cpu_core,cpu_used,cpu_free)
        email_t = host.query.filter_by(hostname=hostname).first().user_info.email
        warn.cpu_warn(cpu_used,hostname,email_t)
        return response(message="create cpu_info success")

        return "cpu post"
    def put(self,id):
        hostname = request.json.get("hostname")
        date = request.json.get("date")
        cpu_core = request.json.get("cpu_core")
        cpu_used = request.json.get("cpu_used")
        cpu_free = request.json.get("cpu_free")

        cpu_t.update(id, hostname, date, cpu_core, cpu_used, cpu_free)
        return response(message="update cpu_info success")
    def delete(self,id):
        cpu_t.delete(id)
        return response(message="delete cpu_info success")

api.add_resource(cpu,'/cpu')
api.add_resource(cpu,'/cpu/<int:id>',endpoint='cpuid')





